package com.qb.devstore;

import static com.qb.devstore.ViewActivity.vActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import utils.AppUtil;
import utils.ImgUtil;
import utils.MyUtil;

public class AppAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private Context mCtx;
    private JSONArray mData;
    private List<Boolean> isClicks;

    public AppAdapter(Context ctx, JSONArray data) {
        MyUtil.showLog("AppAdapter",data);
        try {
            data.length();
        } catch (Exception e) {
            e.printStackTrace();
            data = new JSONArray();
        }
        mCtx = ctx;
        mData = data;
        isClicks = new ArrayList<>();
        for (int i = 0; i < data.length(); i++) {
            isClicks.add(false);
            if (i == 0) {
                isClicks.set(0, true);
            }
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_layout, parent, false);
        return new MHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        MHolder mHolder = (MHolder) holder;
        try {
            String apkName,apkVersion = null,apkMem = null,apkIcon = null,apkUrl;
            JSONObject o = new JSONObject(mData.get(position).toString());
            apkName = o.getString("name");
            mHolder.label.setText(apkName);
            try {
                // 本地app版本
                apkVersion = "v"+o.getString("versionName");
                mHolder.version.setText(apkVersion);
            } catch (Exception e) {
                //e.printStackTrace();
            }
            try {
                // 应用商店app版本
                apkVersion = "v"+o.getString("version");
                int l = apkVersion.length() >= 10 ? 10 : apkVersion.length();
                mHolder.version.setText(apkVersion.substring(0, l));
            } catch (Exception e) {
                //e.printStackTrace();
            }
            try {
                // 本地已安装app备注
                mHolder.mem.setText(o.getString("dtInstall")+"安装");
            } catch (Exception e) {
                // e.printStackTrace();
            }
            String size = "";
            try {
                double dSize = o.getDouble("size")/1024/1024;
                DecimalFormat df = new DecimalFormat("0.0");
                size = "【"+df.format(dSize)+"MB】";
            } catch (Exception e){}
            try {
                // 应用商店app备注
                apkMem = o.getString("remark");
                mHolder.mem.setText(size+apkMem);
            } catch (Exception e) {
               // e.printStackTrace();
            }
            try {
                ImgUtil iu = new ImgUtil();
                apkIcon = o.getString("icon");
                Drawable drawable = iu.bitmap2Drawable(iu.getimg(apkIcon));
                drawable.setBounds(0, 0, 96,96);
                mHolder.icon.setImageDrawable(drawable);
            }catch (Exception e) {}
            try {
                apkIcon = o.getString("appicon");
                MyUtil.showLog("appicon", apkIcon);
                requestImg(mHolder.icon,new URL(apkIcon));
            } catch (Exception e) {
                // e.printStackTrace();
            }
            try {
                String packageName = "";
                try {
                    packageName = o.getString("packageName");
                    packageName = "本地应用列表";
                } catch (Exception e) {}
                try {
                    packageName = o.getString("package_name");
                } catch (Exception e) {}
                MyUtil.showLog("getAppStatus packageName",packageName);
                mHolder.btnInstall.setVisibility(View.GONE);
                mHolder.btnUpdate.setVisibility(View.GONE);
                mHolder.btnStatus.setVisibility(View.GONE);
                String app_status = AppUtil.getAppStatus(mCtx,packageName,o.getInt("ver_order"));
                if (!packageName.equals("本地应用列表")) {
                    if (app_status.equals("installed")) {
                        mHolder.btnStatus.setVisibility(View.VISIBLE);
                    } else if (app_status.equals("update")) {
                        mHolder.btnUpdate.setVisibility(View.VISIBLE);
                    } else {
                        mHolder.btnInstall.setVisibility(View.VISIBLE);
                    }
                }
            } catch (Exception e) {
               // e.printStackTrace();
            }
            try {
                apkUrl = o.getString("url");
                final String ver = apkVersion;
                final String mem = apkMem;
                final String icon = apkIcon;
                String finalSize = size;
                mHolder.btnInstall.setOnClickListener(view -> {
                    dLoadInActivity(apkName,ver,mem,icon,apkUrl,finalSize);
//                    if (AppUtil.downloadNum>=5) {
//                        XToastUtils.warning("最多同时进行5个下载任务",1500);
//                    } else {
//                        showCustomDialog(apkName,apkUrl,"install");
//                    }
                });
                String finalSize1 = size;
                mHolder.btnUpdate.setOnClickListener(view -> {
                    dLoadInActivity(apkName,ver,mem,icon,apkUrl,finalSize1);
//                    if (AppUtil.downloadNum>=5) {
//                        XToastUtils.warning("最多同时进行5个下载任务",1500);
//                    } else {
//                        showCustomDialog(apkName,apkUrl,"update");
//                    }
                });
            } catch (Exception e) {
                //e.printStackTrace();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return mData.length();
    }

    public class MHolder extends RecyclerView.ViewHolder {
        public LinearLayout llApp;
        public TextView label,version,mem,btnInstall,btnUpdate,btnStatus;
        public ImageView icon;
        public MHolder(View v) {
            super(v);
            llApp = v.findViewById(R.id.ll_app);
            label = v.findViewById(R.id.tv_app_label);
            version = v.findViewById(R.id.tv_app_version);
            mem = v.findViewById(R.id.tv_app_mem);
            icon = v.findViewById(R.id.iv_app_icon);
            btnInstall = v.findViewById(R.id.btn_app_install);
            btnUpdate = v.findViewById(R.id.btn_app_update);
            btnStatus = v.findViewById(R.id.btn_app_status);
        }
    }

    // 使用通知显示下载进度
    private void showCustomDialog(String apkName,String url,String flag) {
        MaterialDialog.Builder md = new MaterialDialog.Builder(mCtx);
        md.title(apkName);
        md.content("是否确认下载");
        md.positiveText("确定");
        md.onPositive((dialog, which) -> {
            if (flag.equals("install")) AppUtil.dloadApk(mCtx,url,apkName+".apk",false);
            else if (flag.equals("update")) AppUtil.dloadApk(mCtx,url,apkName+".apk",false);
        });
        md.negativeText("取消");
        md.negativeColorRes(R.color.gray);
        md.show();
    }

    // 在TaskActivity中显示下载进度
    private void dLoadInActivity(String apkName,String apkVersion,String apkMem,String apkIcon,String apkUrl,String apkSize) {
        Intent dLoadActivity = new Intent(mCtx,TaskActivity.class);
        dLoadActivity.putExtra("apkName",apkName);
        dLoadActivity.putExtra("apkVersion",apkVersion);
        dLoadActivity.putExtra("apkMem",apkMem);
        dLoadActivity.putExtra("apkIcon",apkIcon);
        dLoadActivity.putExtra("apkUrl",apkUrl);
        dLoadActivity.putExtra("apkSize",apkSize);
        mCtx.startActivity(dLoadActivity);
    }

    private void requestImg(ImageView iv, final URL imgUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = BitmapFactory.decodeStream(imgUrl.openStream());
                    showImg(iv,bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showImg(ImageView iv, final Bitmap bitmap){
        vActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                iv.setImageBitmap(bitmap);
            }
        });
    }
}
